import React, { useState, useEffect } from 'react';
import { Bell, X, Check, AlertTriangle, Info, CheckCircle, Clock, User, FileText, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';

/**
 * 通知类型枚举
 */
export type NotificationType = 'info' | 'success' | 'warning' | 'error' | 'activity';

/**
 * 通知数据接口
 */
export interface Notification {
  id: string;
  type: NotificationType;
  title: string;
  message: string;
  timestamp: Date;
  read: boolean;
  actionUrl?: string;
  userId?: string;
  metadata?: Record<string, any>;
}

/**
 * 活动数据接口
 */
export interface Activity {
  id: string;
  type: 'user_login' | 'user_logout' | 'file_upload' | 'report_generated' | 'system_update' | 'error_occurred';
  title: string;
  description: string;
  timestamp: Date;
  userId?: string;
  userName?: string;
  metadata?: Record<string, any>;
}

/**
 * 通知中心组件属性
 */
interface NotificationCenterProps {
  onNotificationClick?: (notification: Notification) => void;
  onActivityClick?: (activity: Activity) => void;
  maxItems?: number;
}

/**
 * 模拟通知数据生成
 */
const generateMockNotifications = (): Notification[] => {
  const notifications: Notification[] = [
    {
      id: '1',
      type: 'info',
      title: '系统维护通知',
      message: '系统将于今晚23:00-01:00进行例行维护',
      timestamp: new Date(Date.now() - 1000 * 60 * 30), // 30分钟前
      read: false
    },
    {
      id: '2',
      type: 'success',
      title: '报告生成完成',
      message: '月度分析报告已生成完成，请查看',
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 2), // 2小时前
      read: false,
      actionUrl: '/analytics'
    },
    {
      id: '3',
      type: 'warning',
      title: '存储空间不足',
      message: '系统存储空间使用率已达85%，请及时清理',
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 4), // 4小时前
      read: true
    },
    {
      id: '4',
      type: 'error',
      title: '登录异常',
      message: '检测到异常登录尝试，请检查安全设置',
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 6), // 6小时前
      read: false
    }
  ];
  return notifications;
};

/**
 * 模拟活动数据生成
 */
const generateMockActivities = (): Activity[] => {
  const activities: Activity[] = [
    {
      id: '1',
      type: 'user_login',
      title: '用户登录',
      description: '管理员 张三 登录系统',
      timestamp: new Date(Date.now() - 1000 * 60 * 15), // 15分钟前
      userId: 'user1',
      userName: '张三'
    },
    {
      id: '2',
      type: 'report_generated',
      title: '报告生成',
      description: '系统自动生成了用户活跃度分析报告',
      timestamp: new Date(Date.now() - 1000 * 60 * 45), // 45分钟前
    },
    {
      id: '3',
      type: 'file_upload',
      title: '文件上传',
      description: '用户 李四 上传了新的配置文件',
      timestamp: new Date(Date.now() - 1000 * 60 * 60), // 1小时前
      userId: 'user2',
      userName: '李四'
    },
    {
      id: '4',
      type: 'system_update',
      title: '系统更新',
      description: '系统组件已更新到最新版本',
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 3), // 3小时前
    },
    {
      id: '5',
      type: 'error_occurred',
      title: '错误发生',
      description: '数据库连接出现短暂中断，已自动恢复',
      timestamp: new Date(Date.now() - 1000 * 60 * 60 * 5), // 5小时前
    }
  ];
  return activities;
};

/**
 * 获取通知类型图标
 */
const getNotificationIcon = (type: NotificationType) => {
  const iconMap = {
    info: Info,
    success: CheckCircle,
    warning: AlertTriangle,
    error: X,
    activity: Bell
  };
  const Icon = iconMap[type];
  return <Icon className="w-4 h-4" />;
};

/**
 * 获取活动类型图标
 */
const getActivityIcon = (type: Activity['type']) => {
  const iconMap = {
    user_login: User,
    user_logout: User,
    file_upload: FileText,
    report_generated: FileText,
    system_update: Settings,
    error_occurred: AlertTriangle
  };
  const Icon = iconMap[type];
  return <Icon className="w-4 h-4" />;
};

/**
 * 格式化时间显示
 */
const formatTimeAgo = (timestamp: Date): string => {
  const now = new Date();
  const diff = now.getTime() - timestamp.getTime();
  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  return `${days}天前`;
};

/**
 * 通知中心组件
 */
export const NotificationCenter: React.FC<NotificationCenterProps> = ({
  onNotificationClick,
  onActivityClick,
  maxItems = 10
}) => {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [activities, setActivities] = useState<Activity[]>([]);
  const [activeTab, setActiveTab] = useState<'notifications' | 'activities'>('notifications');

  /**
   * 初始化数据
   */
  useEffect(() => {
    setNotifications(generateMockNotifications());
    setActivities(generateMockActivities());

    // 模拟实时数据更新
    const interval = setInterval(() => {
      // 随机添加新通知
      if (Math.random() > 0.8) {
        const newNotification: Notification = {
          id: Date.now().toString(),
          type: ['info', 'success', 'warning'][Math.floor(Math.random() * 3)] as NotificationType,
          title: '新通知',
          message: '这是一条实时生成的通知消息',
          timestamp: new Date(),
          read: false
        };
        setNotifications(prev => [newNotification, ...prev.slice(0, maxItems - 1)]);
      }

      // 随机添加新活动
      if (Math.random() > 0.7) {
        const activityTypes: Activity['type'][] = ['user_login', 'file_upload', 'report_generated'];
        const newActivity: Activity = {
          id: Date.now().toString(),
          type: activityTypes[Math.floor(Math.random() * activityTypes.length)],
          title: '新活动',
          description: '这是一条实时生成的活动记录',
          timestamp: new Date()
        };
        setActivities(prev => [newActivity, ...prev.slice(0, maxItems - 1)]);
      }
    }, 30000); // 每30秒检查一次

    return () => clearInterval(interval);
  }, [maxItems]);

  /**
   * 标记通知为已读
   */
  const markAsRead = (notificationId: string) => {
    setNotifications(prev => 
      prev.map(notification => 
        notification.id === notificationId 
          ? { ...notification, read: true }
          : notification
      )
    );
  };

  /**
   * 删除通知
   */
  const removeNotification = (notificationId: string) => {
    setNotifications(prev => prev.filter(n => n.id !== notificationId));
  };

  /**
   * 获取未读通知数量
   */
  const unreadCount = notifications.filter(n => !n.read).length;

  return (
    <Card className="w-full max-w-md">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg flex items-center space-x-2">
            <Bell className="w-5 h-5" />
            <span>通知中心</span>
            {unreadCount > 0 && (
              <Badge variant="destructive" className="text-xs">
                {unreadCount}
              </Badge>
            )}
          </CardTitle>
        </div>
        <div className="flex space-x-1">
          <Button
            variant={activeTab === 'notifications' ? 'default' : 'ghost'}
            size="sm"
            onClick={() => setActiveTab('notifications')}
            className="flex-1"
          >
            通知
          </Button>
          <Button
            variant={activeTab === 'activities' ? 'default' : 'ghost'}
            size="sm"
            onClick={() => setActiveTab('activities')}
            className="flex-1"
          >
            活动
          </Button>
        </div>
      </CardHeader>
      <CardContent className="p-0">
        <ScrollArea className="h-96">
          {activeTab === 'notifications' ? (
            <div className="space-y-1">
              {notifications.length === 0 ? (
                <div className="p-4 text-center text-muted-foreground">
                  <Bell className="w-8 h-8 mx-auto mb-2 opacity-50" />
                  <p>暂无通知</p>
                </div>
              ) : (
                notifications.map((notification, index) => (
                  <div key={notification.id}>
                    <div 
                      className={`p-3 hover:bg-muted/50 cursor-pointer transition-colors ${
                        !notification.read ? 'bg-blue-50 border-l-4 border-l-blue-500' : ''
                      }`}
                      onClick={() => {
                        markAsRead(notification.id);
                        onNotificationClick?.(notification);
                      }}
                    >
                      <div className="flex items-start space-x-3">
                        <div className={`flex-shrink-0 p-1 rounded-full ${
                          notification.type === 'success' ? 'bg-green-100 text-green-600' :
                          notification.type === 'warning' ? 'bg-yellow-100 text-yellow-600' :
                          notification.type === 'error' ? 'bg-red-100 text-red-600' :
                          'bg-blue-100 text-blue-600'
                        }`}>
                          {getNotificationIcon(notification.type)}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between">
                            <p className="text-sm font-medium truncate">
                              {notification.title}
                            </p>
                            <div className="flex items-center space-x-1">
                              <span className="text-xs text-muted-foreground">
                                {formatTimeAgo(notification.timestamp)}
                              </span>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-6 w-6 p-0"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  removeNotification(notification.id);
                                }}
                              >
                                <X className="w-3 h-3" />
                              </Button>
                            </div>
                          </div>
                          <p className="text-xs text-muted-foreground mt-1">
                            {notification.message}
                          </p>
                        </div>
                      </div>
                    </div>
                    {index < notifications.length - 1 && <Separator />}
                  </div>
                ))
              )}
            </div>
          ) : (
            <div className="space-y-1">
              {activities.length === 0 ? (
                <div className="p-4 text-center text-muted-foreground">
                  <Clock className="w-8 h-8 mx-auto mb-2 opacity-50" />
                  <p>暂无活动记录</p>
                </div>
              ) : (
                activities.map((activity, index) => (
                  <div key={activity.id}>
                    <div 
                      className="p-3 hover:bg-muted/50 cursor-pointer transition-colors"
                      onClick={() => onActivityClick?.(activity)}
                    >
                      <div className="flex items-start space-x-3">
                        <div className="flex-shrink-0 p-1 rounded-full bg-gray-100 text-gray-600">
                          {getActivityIcon(activity.type)}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between">
                            <p className="text-sm font-medium truncate">
                              {activity.title}
                            </p>
                            <span className="text-xs text-muted-foreground">
                              {formatTimeAgo(activity.timestamp)}
                            </span>
                          </div>
                          <p className="text-xs text-muted-foreground mt-1">
                            {activity.description}
                          </p>
                        </div>
                      </div>
                    </div>
                    {index < activities.length - 1 && <Separator />}
                  </div>
                ))
              )}
            </div>
          )}
        </ScrollArea>
      </CardContent>
    </Card>
  );
};

export default NotificationCenter;